import { useLayoutStore } from "../store/index";
import event from '../util/event';

let commondStore: any;

export default function useCommond() {
  if (commondStore) {
    return commondStore;
  }

  let useLayout = useLayoutStore();

  commondStore = {
    queue: [],
    currentIndex: -1,
    commond: [],
    pushCommond: pushCommond,
    undo: undo,
    redo: redo,
    log: log,
  };

  function undo() {
    if (commondStore.currentIndex === -1) {
      return;
    } else {
      let commond = commondStore.queue[commondStore.currentIndex];
      if (commond && commond.undo) {
        commond.undo();
      }
      commondStore.currentIndex--;
    }
  }

  function redo() {
    if (commondStore.queue[commondStore.currentIndex + 1]) {
      let commond = commondStore.queue[commondStore.currentIndex + 1];
      if (commond.redo) {
        commond.redo();
      }
      commondStore.currentIndex++;
    }
  }

  function pushCommond(commond: any) {
    let { before, after } = commond;

    //撤销操作后进行命令注册，需移除撤销后面的命令
    if (commondStore.currentIndex !== -1) {
      commondStore.queue = commondStore.queue.slice(
        0,
        commondStore.currentIndex + 1
      );
    }

    commondStore.queue.push({
      //撤销操作
      undo() {
        useLayout.update(JSON.parse(before));
      },
      //重新执行
      redo() {
        useLayout.update(JSON.parse(after));
      },
    });

    commondStore.currentIndex++;
  }

  function log() {
    console.log(commondStore.queue, commondStore.currentIndex);
  }

  let before:any;

  event.on('before-record',() => {
    before = JSON.stringify(useLayout)
  })

  event.on('after-record',() => {
    if(before){
      commondStore.pushCommond({before,after:JSON.stringify(useLayout)});
      before = undefined;
    }
  })

  return commondStore;
}
